import { Controller, Post, Body, UseGuards, Req, BadGatewayException, Get, Delete, Query } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth, ApiProperty } from '@nestjs/swagger';
import { InjectModel } from 'nestjs-typegoose';
import { User } from '@libs/db/models/user.models';
import { AuthGuard } from "@nestjs/passport"
import { LoginDto } from "./dto/login.dto"
import { RegisterDto } from "./dto/register.dto"
import { ModelType } from '@typegoose/typegoose/lib/types';
import { SetPass } from './dto/setpass.dto';
import { IsString } from 'class-validator';
import { ProjectConfig } from './auth.config';
import { sign } from "jsonwebtoken"

class Page {
    @IsString()
    @ApiProperty({ description: '当前页数' })
    page: number
}
class Userid {
    @IsString()
    @ApiProperty({ description: '用户id' })
    userid: string
}


@Controller('auth')
@ApiTags('用户模块')
export class AuthController {
    constructor(
        @InjectModel(User) private userModel: ModelType<User>
    ) { };



    @ApiOperation({ summary: "注册" })
    @Post("register")
    async register(@Body() data: RegisterDto): Promise<Object> {
        let { username } = data;
        data.time = Math.floor(Date.now() / 1000)
        let uniqu = await this.userModel.find({ username })
        if (uniqu.length === 0) {
            let user = await this.userModel.create(data)
            return user
        } else {
            throw new BadGatewayException("该用户已注册")
        }
    }



    @ApiOperation({ summary: "登录" })
    @Post("login")
    @UseGuards(AuthGuard("local"))
    async login(@Body() data: LoginDto, @Req() req): Promise<Object> {
        return {
            id: req.user._id,
            username: data.username,
            token: sign({ exp: Math.floor(Date.now() / 1000) + (24 * 60 * 60), data: req.user._id }, ProjectConfig.SECRET)
        };
    }



    @ApiOperation({ summary: "查询用户列表" })
    @Get("userlist")
    @ApiBearerAuth()
    @UseGuards(AuthGuard("jwt"))
    async userlist(@Query() body: Page, @Req() req): Promise<Object> {

        if (req.user.username == "admin") {
            let count = await this.userModel.countDocuments()
            let userlist = await this.userModel.find().skip((body.page - 1) * 10).limit(10).sort({ '_id': -1 });
            return { total: count, date: userlist }
        } else {
            throw new BadGatewayException("暂无无权限")
        }
    }



    @ApiOperation({ summary: "修改用户密码" })
    @Post("setpass")
    @ApiBearerAuth()
    @UseGuards(AuthGuard("jwt"))
    @UseGuards(AuthGuard("local"))
    async setpass(@Body() body: SetPass, @Req() req): Promise<Object> {
        let setpass = await this.userModel.updateOne({ _id: req.user._id }, { password: body.setpassword })
        return setpass

    }



    @ApiOperation({ summary: "删除用户" })
    @Delete("deuser")
    @ApiBearerAuth()
    @UseGuards(AuthGuard("jwt"))
    async deuser(@Body() body: Userid, @Req() req): Promise<Object> {
        if (req.user.username == "admin") {
            let deuser = await this.userModel.deleteOne({ _id: body.userid })
            return deuser
        } else {
            throw new BadGatewayException("暂无无权限")
        }
    }
}